package com.yfker.pda.utils;

import com.blankj.utilcode.util.EncodeUtils;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class AESUtilHelp {


    /**
     * AES-128-ECB 加密
     * @param src
     * @param secret
     * @return
     * @throws Exception
     */
    public static String Encrypt(String src, String secret) {
        if (secret == null) {
            return null;
        }

        // 加密key为16位
        if (secret.length() != 16) {
            return null;
        }

        byte[] raw = secret.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8));
            return EncodeUtils.base64Encode2String(encrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
